package com.ctshk.rpc.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SeasonType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.season.dto.*;
import com.ctshk.rpc.season.entity.*;
import com.ctshk.rpc.season.mapper.*;
import com.ctshk.rpc.season.req.*;
import com.ctshk.rpc.season.service.*;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 套票产品成本策略表 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-15
 */
@Slf4j
@DubboService
public class SeasonProductStrategyServiceImpl extends ServiceImpl<SeasonProductStrategyMapper, SeasonProductStrategy> implements ISeasonProductStrategyService {
    @Autowired
    private ISeasonFixedProductService seasonFixedProductService;


    @Autowired
    private ISeasonProductStrategyVaildDateService seasonProductStrategyVaildDateService;

    @Autowired
    private ISeasonProductChannelOfflineService seasonProductChannelOfflineService;

    @Autowired
    private SeasonProductStrategyNotesMapper seasonProductStrategyNotesMapper;

    @Autowired
    private SeasonProductStrategyMapper seasonProductStrategyMapper;

    //固定套票
    @Autowired
    private SeasonFixedProductMapper seasonFixedProductMapper;

    //策略日期设置
    @Autowired
    private SeasonProductStrategyVaildDateMapper seasonProductStrategyVaildDateMapper;


    //  固定套票 加幅策略 线下自营 自定义用权限 Mapper 接口
    @Autowired
    private SeasonProductChannelOfflineMapper seasonProductChannelOfflineMapper;

    //套票线下 线下 代理商渠道
    @Autowired
    private SeasonProductChannelOfflineAgentCustomMapper seasonProductChannelOfflineAgentCustomMapper;

    //套票线下 自营 自定义 具体
    @Autowired
    private ISeasonProductChannelOfflineSelfCustomService seasonProductChannelOfflineSelfCustomService;

    @Autowired
    private SeasonProductChannelOfflineSelfCustomMapper seasonProductChannelOfflineSelfCustomMapper;
    @Autowired
    private ISeasonProductChannelOfflineAgentCustomService seasonProductChannelOfflineAgentCustomService;
    @Autowired
    private ISeasonProductChannelOnlineThirdPlatformService seasonProductChannelOnlineThirdPlatformService;
    @Autowired
    private ISeasonProductChannelOnlineSelfPlatformService seasonProductChannelOnlineSelfPlatformService;
    @Autowired
    private ISeasonProductStrategyNotesService notesService;

    //线上官方平台
    @Autowired
    private SeasonProductChannelOnlineSelfPlatformMapper seasonProductChannelOnlineSelfPlatformMapper;

    //线上 第三方平台
    @Autowired
    private SeasonProductChannelOnlineThirdPlatformMapper seasonProductChannelOnlineThirdPlatformMapper;

    @DubboReference
    private ISysDepartmentService sysDepartmentService;

    @DubboReference
    private ISysPermissionService sysPermissionService;

    /* @MethodName: 产品中心 固定套票搜索列表
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/15 15:08
     **/
    @Override
    public PageResponse<FixedSeasonProductPageDTO> searchProductCenterSeasonFixed(SearchFixedProductReq req, TokenUser user) {
        //搜索固定套票列表
        req.setSellStatus(SeasonType.VALID.getCode());
        req.setApprovalStatus(SeasonType.REVIEW_PASS.getCode());
        return seasonFixedProductService.searchSeasonFixedProduct(req, user);
    }

    /* @MethodName: 保存固定套票 加幅策略信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/15 17:50
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveSeasonProductStrategy(SeasonProductStrategyInfoReq infoReq, TokenUser user) {
        if (null == user) {
            return Result.failed(SystemError.USER_1000);
        }
        List<SeasonProductStrategyReq> strategyReqList = infoReq.getStrategyList();
        if (null == strategyReqList || strategyReqList.size() == 0) {
            return Result.failed(SystemError.SEASON_TICKET_20007);
        }
        Long seasonProductId = infoReq.getSeasonProductId();
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(seasonProductId);
        if (null == seasonFixedProduct) {//固定套票为空
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        //是否审核通过
        boolean ifReview = SeasonType.REVIEW_PASS.getCode().equals(seasonFixedProduct.getApprovalStatus());
        //是否有效
        boolean ifValid = SeasonType.VALID.getCode() == seasonFixedProduct.getSellStatus();
        //当没有审核通过的时候  或者是无效的时候 不能进行
        if (ifReview == false || ifValid == false) {
            return Result.failed(SystemError.SEASON_TICKET_20008);
        }
        //套票产品
        List<SeasonProductStrategy> seasonProductStrategyList = getSeasonProductStrategyList(seasonProductId);
        //检查固定套票策略日期设置 是否正确
        Result result = checkSeasonProductStrategyDate(strategyReqList);
        if (!result.isSuccess()) {
            return result;
        }
        //套票备注信息
        notesService.saveOrUpdateSeasonProductNotes(seasonProductId, infoReq.getStoreNotes(), infoReq.getDeptNotes(), infoReq.getSupplierNotes(), user.getId());
        //当查询结果为空的时候 表示没有进行 加幅策略
        boolean onShelfStatus = false;
        if (null != seasonProductStrategyList && seasonProductStrategyList.size() > 0) {//不为空的时候 就表示 是修改
            onShelfStatus = updateSeasonProductStrategyInfo(strategyReqList, user.getId(), seasonProductId);
        } else {
            //保存固定套票加幅策略
            onShelfStatus = addSeasonProductStrategy(strategyReqList, user.getId(), seasonProductId);
        }
        if (onShelfStatus) {//onShelfStatus=false;//当为true 就是上架状态产品
            seasonFixedProductService.onShelfProduct(seasonProductId, SeasonType.IS_ONSHELF.getCode());
        }
        return Result.success();
    }

    /* @MethodName: 检查固定套票策略日期 设置是否合理
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/16 18:07
     **/
    private Result checkSeasonProductStrategyDate(List<SeasonProductStrategyReq> reqList) {
        List<SeasonProductStrategyVaildDateReq> seasonProductStrategyVaildDateReqList = new LinkedList<>();
        for (SeasonProductStrategyReq strategyReq : reqList) {
            List<SeasonProductStrategyVaildDateReq> seasonProductStrategyVaildDateList = strategyReq.getSeasonProductStrategyVaildDateList();
            if (null != seasonProductStrategyVaildDateList && seasonProductStrategyVaildDateList.size() > 0) {
                seasonProductStrategyVaildDateReqList.addAll(strategyReq.getSeasonProductStrategyVaildDateList());
            } else {
                continue;
            }
        }
        for (int i = 0; i < seasonProductStrategyVaildDateReqList.size(); i++) {
            SeasonProductStrategyVaildDateReq seasonProductStrategyVaildDateReq = seasonProductStrategyVaildDateReqList.get(i);
            if (seasonProductStrategyVaildDateReq.getTimeBegin().isBefore(LocalDate.now())) {
                // 固定套票产品加幅策略保存，开始日期不能小于当前日期校验
                return Result.failed(SystemError.SHIP_PRODUCT_11019);
            }
            if (i == 0 && seasonProductStrategyVaildDateReq.getTimeBegin().isAfter(seasonProductStrategyVaildDateReq.getTimeEnd())) {
                // 开始日期必须小于结束日期校验
                return Result.failed(SystemError.SHIP_PRODUCT_11020);
            }
            for (int j = 0; j < seasonProductStrategyVaildDateReqList.size(); j++) {
                SeasonProductStrategyVaildDateReq strategyDateReqTemp = seasonProductStrategyVaildDateReqList.get(j);
                if (i >= j) { // 自身和已经校验过的跳过日期校验
                    continue;
                }
                if (i == 0 && strategyDateReqTemp.getTimeBegin().isAfter(strategyDateReqTemp.getTimeEnd())) {
                    // 开始日期必须小于结束日期校验
                    return Result.failed(SystemError.SHIP_PRODUCT_11019);
                }
                if (DateUtil.isDateRange(seasonProductStrategyVaildDateReq.getTimeBegin(), seasonProductStrategyVaildDateReq.getTimeEnd(), strategyDateReqTemp.getTimeBegin(), strategyDateReqTemp.getTimeEnd())) {
                    // 当前日期与其他日期区域重叠校验
                    return Result.failed(SystemError.SHIP_PRODUCT_11021);
                }
            }
        }
        return Result.success();
    }

    /* @MethodName: 根据产品 id 获取固定套票详情
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/16 15:28
     **/
    @Override
    public Result queryByProductId(Long productId) {
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(productId);
        if (Objects.isNull(seasonFixedProduct)) {
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        SeasonProductStrategyInfoDTO infoDTO = new SeasonProductStrategyInfoDTO();
        SeasonProductStrategyNotes notes = seasonProductStrategyNotesMapper.selectOne(new QueryWrapper<SeasonProductStrategyNotes>().lambda().eq(SeasonProductStrategyNotes::getSeasonProductId, productId));
        if (notes != null) {
            infoDTO = EntityUtil.copy(notes, SeasonProductStrategyInfoDTO.class);
        }
        List<SeasonProductStrategyDTO> strategyDtoList = new LinkedList<>();
        //获取策略信息
        List<SeasonProductStrategy> productStrategyList = seasonProductStrategyMapper.selectList(
                new QueryWrapper<SeasonProductStrategy>().lambda().eq(SeasonProductStrategy::getSeasonProductId, productId)
                        .eq(SeasonProductStrategy::getIsDeleted, IsDeletedCode.NO.getCode())
        );
        if (null != productStrategyList && productStrategyList.size() > 0) {
            for (SeasonProductStrategy strategy : productStrategyList) {
                SeasonProductStrategyDTO strategyDTO = EntityUtil.copy(strategy, SeasonProductStrategyDTO.class);
                getSeasonProductStrategyDTO(productId, strategyDTO);
                strategyDtoList.add(strategyDTO);
            }

        }
        infoDTO.setStrategyList(strategyDtoList);
        return Result.success(infoDTO);
    }

    private void getSeasonProductStrategyDTO(Long productId, SeasonProductStrategyDTO strategyDTO) {
        strategyDTO.setProductId(productId);
        //策略id
        Long strategyId = strategyDTO.getId();
        //有效期
        List<SeasonProductStrategyVaildDate> vaildDatesList = seasonProductStrategyVaildDateMapper.selectList(
                new QueryWrapper<SeasonProductStrategyVaildDate>().lambda().eq(SeasonProductStrategyVaildDate::getStrategyId, strategyId)
                        .eq(SeasonProductStrategyVaildDate::getIsDeleted, IsDeletedCode.NO.getCode())
        );
        List<SeasonProductStrategyVaildDateReq> vaildDateReqList = EntityUtil.copyList(vaildDatesList, SeasonProductStrategyVaildDateReq.class);

        strategyDTO.setSeasonProductStrategyVaildDateList(vaildDateReqList);
        //线下 自营渠道
        List<SeasonProductChannelOffline> seasonProductChannelOfflineList = seasonProductChannelOfflineMapper.selectList(
                new QueryWrapper<SeasonProductChannelOffline>().lambda().eq(SeasonProductChannelOffline::getProductId, productId)
                        .eq(SeasonProductChannelOffline::getStrategyId, strategyId).eq(SeasonProductChannelOffline::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(SeasonProductChannelOffline::getChannelType, SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode())

        );
        if (null != seasonProductChannelOfflineList && seasonProductChannelOfflineList.size() > 0) {
            List<SeasonProductChannelOfflineSelfCustomDTO> selfCustomDTOList = EntityUtil.copyList(seasonProductChannelOfflineList, SeasonProductChannelOfflineSelfCustomDTO.class);
            for (SeasonProductChannelOfflineSelfCustomDTO customDTO : selfCustomDTOList) {
                customDTO.setProductChannelOfflineSelfCustomArrayDTO(
                        EntityUtil.copyList(seasonProductChannelOfflineSelfCustomMapper.selectList(
                                new QueryWrapper<SeasonProductChannelOfflineSelfCustom>().lambda().
                                        eq(SeasonProductChannelOfflineSelfCustom::getOfflineId, customDTO.getId())
                        ), SeasonProductChannelOfflineSelfCustomArrayDTO.class)
                );
            }
            strategyDTO.setSeasonProductChannelOfflineSelfCustomDTOS(selfCustomDTOList);
        }
        //线下代理
        List<SeasonProductChannelOffline> seasonProductChannelOfflineAgentList = seasonProductChannelOfflineMapper.selectList(
                new QueryWrapper<SeasonProductChannelOffline>().lambda().eq(SeasonProductChannelOffline::getProductId, productId)
                        .eq(SeasonProductChannelOffline::getStrategyId, strategyId).eq(SeasonProductChannelOffline::getIsDeleted, IsDeletedCode.NO.getCode())
//                        .eq(SeasonProductChannelOffline::getChannelType, SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode())
                        .eq(SeasonProductChannelOffline::getChannelType, SeasonType.OFFLINE_AGENT_CHANNEL_TYPE.getCode())

        );
        if (null != seasonProductChannelOfflineAgentList && seasonProductChannelOfflineAgentList.size() > 0) {
            List<SeasonProductChannelOfflineAgentCustomDTO> agentCustomDTOList = EntityUtil.copyList(seasonProductChannelOfflineAgentList, SeasonProductChannelOfflineAgentCustomDTO.class);
            for (SeasonProductChannelOfflineAgentCustomDTO agentCustomDTO : agentCustomDTOList) {
                agentCustomDTO.setProductChannelOfflineAgentCustomArray(
                        EntityUtil.copyList(seasonProductChannelOfflineAgentCustomMapper.selectList(
                                new QueryWrapper<SeasonProductChannelOfflineAgentCustom>().lambda().
                                        eq(SeasonProductChannelOfflineAgentCustom::getOfflineId, agentCustomDTO.getId())
                        ), SeasonProductChannelOfflineAgentCustomArrayReq.class)
                );
            }
            strategyDTO.setSeasonProductChannelOfflineAgentCustomListDTOS(agentCustomDTOList);
        }
        //线上自营
        List<SeasonProductChannelOnlineSelfPlatform> selfPlatformList = seasonProductChannelOnlineSelfPlatformMapper.selectList(
                new QueryWrapper<SeasonProductChannelOnlineSelfPlatform>().lambda().eq(SeasonProductChannelOnlineSelfPlatform::getStrategyId, strategyId)
        );
        strategyDTO.setSeasonProductChannelOnlineSelfPlatformList(EntityUtil.copyList(selfPlatformList, SeasonProductChannelOnlineSelfPlatformReq.class));
        //线上第三方
        List<SeasonProductChannelOnlineThirdPlatform> thirdPlatformList = seasonProductChannelOnlineThirdPlatformMapper.selectList(
                new QueryWrapper<SeasonProductChannelOnlineThirdPlatform>().lambda().eq(SeasonProductChannelOnlineThirdPlatform::getStrategyId, strategyId)
        );
        strategyDTO.setSeasonProductChannelOnlineThirdPlatformList(EntityUtil.copyList(thirdPlatformList, SeasonProductChannelOnlineThirdPlatformReq.class));
    }

    /* @MethodName: 根据套票id 跟日期获取 日期套票加幅信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/17 9:14
     **/
    @Override
    public Result queryBydate(SeasonProductStrategyQueryByDateReq queryByDateReq) {
        Long productId = queryByDateReq.getProductId();//产品id
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(productId);
        if (Objects.isNull(seasonFixedProduct)) {//固定套票为空
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        FixedSeasonDetailsDTO fixedSeasonDetailsDTO = EntityUtil.copy(seasonFixedProduct, FixedSeasonDetailsDTO.class);
        SeasonProductStrategyNotes notes = seasonProductStrategyNotesMapper.selectOne(new QueryWrapper<SeasonProductStrategyNotes>().lambda().eq(
                SeasonProductStrategyNotes::getSeasonProductId, productId
        ));
        if (!Objects.isNull(notes)) {
            fixedSeasonDetailsDTO.setStoreNotes(notes.getStoreNotes());
            fixedSeasonDetailsDTO.setDeptNotes(notes.getDeptNotes());
            fixedSeasonDetailsDTO.setSupplierNotes(notes.getSupplierNotes());
        }
        fixedSeasonDetailsDTO.setProductId(productId);
        //查询两个日期中的间隔日期
        List<LocalDate> sectionList = DateUtil.getSectionDate(queryByDateReq.getQueryStartDate(), queryByDateReq.getQueryEndDate());
        List<StrategyInfoDateDTO> strategyInfoDateList = new LinkedList();
        //根据产品id 获取策率有效期集合
        List<SeasonProductStrategyVaildDate> vaildDateList = seasonProductStrategyVaildDateMapper.getVaildDateListByProductId(productId);

        for (LocalDate day : sectionList) {
            StrategyInfoDateDTO dto = new StrategyInfoDateDTO();
            dto.setDate(day);
            //根据日期跟产产品id 查询改日期 是否设置有
            if (checkDateYes(vaildDateList, day)) {//当不能为空表示有
                dto.setIsOptional(1);
                SeasonProductStrategyDTO strategyDTO = seasonProductStrategyMapper.querySaleStrategy(productId, day);
                getSeasonProductStrategyDTO(productId, strategyDTO);
                dto.setSeasonProductStrategyDTO(strategyDTO);
            } else {
                dto.setIsOptional(0);
            }
            strategyInfoDateList.add(dto);
        }
        fixedSeasonDetailsDTO.setStrategyInfoDateList(strategyInfoDateList);
        return Result.success(fixedSeasonDetailsDTO);
    }

    /* @MethodName: 检查R某天是否在某个 策略日期中
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/17 18:23
     **/
    private boolean checkDateYes(List<SeasonProductStrategyVaildDate> vaildDateList, LocalDate day) {
        List<String> list = new LinkedList<>();
        if (null != vaildDateList && vaildDateList.size() > 0) {
            for (SeasonProductStrategyVaildDate vaildDate : vaildDateList) {
                boolean flag = DateUtil.isDateRange(day, vaildDate.getTimeBegin(), vaildDate.getTimeEnd());
                if (flag) {
                    list.add("1");
                }
            }
        }
        return list.size() > 0 ? true : false;
    }

    /* @MethodName: 给产品设置推荐
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/17 11:28
     **/
    @Override
    public Result setRecommend(Long productId, Integer isRecommend) {
        SeasonFixedProduct seasonFixedProduct = seasonFixedProductMapper.selectById(productId);
        if (Objects.isNull(seasonFixedProduct)) {//固定套票为空
            return Result.failed(SystemError.SEASON_TICKET_20004);
        }
        seasonFixedProduct.setIsRecommend(isRecommend);
        seasonFixedProductMapper.updateById(seasonFixedProduct);
        return Result.success();
    }


    /* @MethodName: 根据用户id 日期 产品id 获取加幅信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/18 11:30
     **/
    @Override
    public SeasonProductChannelSetInfoDTO getProductStrategyByUserIdDate(Long useId, LocalDate date, Long productId, Integer channelType) {
        SeasonProductChannelSetInfoDTO seasonProductChannelSetInfoDTO = null;
        List<SeasonProductStrategy> strategys = getProductStrategy(productId, date);
        if (strategys != null && strategys.size() > 0) {
            //线下渠道加幅信息
            if (SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode() == channelType || SeasonType.OFFLINE_AGENT_CHANNEL_TYPE.getCode() == channelType) {
                List<SeasonProductChannelOfflineDTO> offlineList = seasonProductChannelOfflineService.geOfflineListByStrategyId(strategys.get(0).getId());
                if (null != offlineList && offlineList.size() > 0) {
                    for (SeasonProductChannelOfflineDTO offline : offlineList) {
                        Long offlineId = offline.getId();//
                        Integer visableType = offline.getVisableType();//权限类型 1：自营禁售 2 所有部门 3指定部门/人员
                        // Integer channelType = offline.getChannelType();//线下渠道类型 1 ：自营渠道 2：代理商
                        //线下自营项目
                        if (SeasonType.OFFLINE_SELF_CHANNEL_TYPE.getCode() == channelType) {
                            List<SeasonProductChannelOfflineSelfCustomArrayDTO> selfCustomList = seasonProductChannelOfflineSelfCustomService.getSetInfoByOfflineId(offlineId);
                            if (null != selfCustomList && selfCustomList.size() > 0) {
                                if (SeasonType.ALL_DEPARTMENT.getCode() == visableType) {  //所有部门 那就取一条数据
                                    seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustomList.get(0), SeasonProductChannelSetInfoDTO.class);
                                } else if (SeasonType.ASSIGN_VISABLE.getCode() == visableType) {
                                    //指定部门 或者人的时候
                                    for (SeasonProductChannelOfflineSelfCustomArrayDTO selfCustom : selfCustomList) {
                                        Long relationId = selfCustom.getRelationId();
                                        if (SeasonType.CHECK_EMPLOYEE.getCode() == selfCustom.getCheckType()) { //勾选员工
                                            if (relationId == useId) {
                                                seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustom, SeasonProductChannelSetInfoDTO.class);
                                            }
                                        } else if (SeasonType.CHECK_DEPARTMENT.getCode() == selfCustom.getCheckType()) { //勾选部门
                                            if (sysDepartmentService.isExist(relationId, useId)) {//表示该用户在这个部门下
                                                seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustom, SeasonProductChannelSetInfoDTO.class);
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (SeasonType.OFFLINE_AGENT_CHANNEL_TYPE.getCode() == channelType) {
                            List<SeasonProductChannelOfflineAgentCustomArrayDTO> agentCustomList = seasonProductChannelOfflineAgentCustomService.getAgentByOfflineId(offlineId);
                            if (null != agentCustomList && agentCustomList.size() > 0) {
                                if (SeasonType.ALL_DEPARTMENT.getCode() == visableType) {  //所有部门 那就取一条数据
                                    seasonProductChannelSetInfoDTO = EntityUtil.copy(agentCustomList.get(0), SeasonProductChannelSetInfoDTO.class);
                                } else if (SeasonType.ASSIGN_VISABLE.getCode() == visableType) {
                                    //指定部门 或者人的时候
                                    for (SeasonProductChannelOfflineAgentCustomArrayDTO selfCustom : agentCustomList) {
                                        Long relationId = selfCustom.getRelationId();
                                        if (SeasonType.CHECK_EMPLOYEE.getCode() == selfCustom.getCheckType()) { //勾选员工
                                            if (relationId == useId) {
                                                seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustom, SeasonProductChannelSetInfoDTO.class);
                                            }
                                        } else if (SeasonType.CHECK_DEPARTMENT.getCode() == selfCustom.getCheckType()) { //勾选部门
                                            if (sysDepartmentService.isExist(relationId, useId)) {//表示该用户在这个部门下
                                                seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustom, SeasonProductChannelSetInfoDTO.class);
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            } else if (SeasonType.ONLINE_SELF_CHANNEL_TYPE.getCode() == channelType) {

                log.info("strategys size : "+ strategys.size());
                log.info("strategys get 0 : "+ strategys.get(0).getId());

                List<SeasonProOnlineSelfCustomDTO> onlineSelf = seasonProductChannelOnlineSelfPlatformService.getOnlineSelfByStrategyId(strategys.get(0).getId());
                if (null != onlineSelf && onlineSelf.size() > 0) {
                    for (SeasonProOnlineSelfCustomDTO selfCustom : onlineSelf) {
                        //if (selfCustom.getChannelId() == useId) {
                        seasonProductChannelSetInfoDTO = EntityUtil.copy(selfCustom, SeasonProductChannelSetInfoDTO.class);
                        log.info("加幅 selfCustom getAdjustType"+selfCustom.getAdjustType());
                        log.info("加幅 selfCustom getChannelName"+selfCustom.getChannelName());
                        break;
                        // }
                    }

                }
            } else if (SeasonType.ONLINE_SELF_CHANNEL_TYPE.getCode() == channelType) {
                //seasonProductChannelOnlineThirdPlatformService
            }


        }
        return seasonProductChannelSetInfoDTO;
    }

    /* @MethodName: 根据固定套票 产品的成本价 算出该产品的 加幅后的总价
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/22 11:00
     **/
    @Override
    public BigDecimal getFixedSeasonAdjustValueByCost(Long userId, LocalDate date, Long productId, BigDecimal cost, Integer channelType) {

        log.info("开始计算加幅金额："+cost);

        BigDecimal bg = cost;
        if (BigDecimal.ZERO.compareTo(bg) <= 0) {
            //获取固定套票的加幅信息
            SeasonProductChannelSetInfoDTO setInfoDTO = getProductStrategyByUserIdDate(userId, date, productId, channelType);

            if (null != setInfoDTO) {

                log.info("获取加幅类型 "+setInfoDTO.getChannelName());
                log.info("getAdjustType "+setInfoDTO.getAdjustType());

                SeasonType adjustTypeEnum = SeasonType.getEnumType(setInfoDTO.getAdjustType(),null);
                log.info("adjustTypeEnum Name "+adjustTypeEnum.getName());

                //加幅类型
                switch (setInfoDTO.getAdjustType()) {
                    //加幅数值
                    case 1:
                        bg = cost.add(setInfoDTO.getAmount());//金额
                        log.info("触发数值加幅策略，加幅后金额："+bg);
                        break;
                    //加幅百分比
                    case 2:
                        long costdoub = Math.round(cost.doubleValue() * setInfoDTO.getPercent());//百分比相乘
                        bg = cost.add(new BigDecimal(costdoub).divide(new BigDecimal(100)));//最后除以100相加
                        log.info("触发百分比加幅策略，加幅后金额："+bg);
                        break;
                }
            }else{
                log.info("未触发任何加幅策略，返回原价");
            }

        }else{
            log.info("成本价为："+cost+"，小于0 不进行任何操作");
        }

        return bg;
    }

    /* @MethodName: 根据时间段 和 产品id 获取 可选的日历信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/23 15:43
     **/
    @Override
    public List<StrategyInfoDateDTO> getOptionalCalendar(SeasonProductStrategyQueryByDateReq req, TokenUser user, Integer channelType) {
        List<StrategyInfoDateDTO> list = new LinkedList();
        //查询两个日期中的间隔日期
        List<LocalDate> sectionList = DateUtil.getSectionDate(req.getQueryStartDate(), req.getQueryEndDate());
        Long productId = req.getProductId();
        Long userId = user.getId();
        //根据产品id 获取策率有效期集合
        List<SeasonProductStrategyVaildDate> vaildDateList = seasonProductStrategyVaildDateMapper.getVaildDateListByProductId(req.getProductId());
        for (LocalDate day : sectionList) {
            StrategyInfoDateDTO dateDTO = new StrategyInfoDateDTO();
            if (checkDateYes(vaildDateList, day)) {//表示 日期在策略的有效期里
                SeasonProductChannelSetInfoDTO dto = getProductStrategyByUserIdDate(userId, day, productId, channelType);
                if (dto != null) {
                    dateDTO.setIsOptional(1);
                } else {
                    dateDTO.setIsOptional(0);
                }
                dateDTO.setDate(day);
                list.add(dateDTO);
            }

        }
        return list;
    }

    //根据产品id 和日期 获取 产品加幅策略
    public List<SeasonProductStrategy> getProductStrategy(Long productId, LocalDate date) {
        //获取该产品下 所有的加幅策略 信息
        return seasonFixedProductMapper.queryStrategyByProductIdDate(productId, date);
    }


    /* @MethodName: 修改套餐产品加幅策略
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/16 11:32
     **/
    private boolean updateSeasonProductStrategyInfo(List<SeasonProductStrategyReq> reqList, Long userId, Long seasonProductId) {
        deleteProductStrategyInfo(seasonProductId);//根据产品中心删除相关数据
        return addSeasonProductStrategy(reqList, userId, seasonProductId);
    }

    /* @MethodName: 删除 具体加幅设置信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/16 14:02
     **/
    private void deleteProductStrategyInfo(Long productId) {
        seasonProductChannelOfflineMapper.delete(new QueryWrapper<SeasonProductChannelOffline>().lambda().eq(SeasonProductChannelOffline::getProductId, productId));
        seasonProductChannelOfflineSelfCustomMapper.delete(new QueryWrapper<SeasonProductChannelOfflineSelfCustom>().lambda().eq(SeasonProductChannelOfflineSelfCustom::getProductId, productId));
        seasonProductChannelOfflineAgentCustomMapper.delete(new QueryWrapper<SeasonProductChannelOfflineAgentCustom>().lambda().eq(SeasonProductChannelOfflineAgentCustom::getProductId, productId));
        seasonProductChannelOnlineSelfPlatformMapper.delete(new QueryWrapper<SeasonProductChannelOnlineSelfPlatform>().lambda().eq(SeasonProductChannelOnlineSelfPlatform::getProductId, productId));
        seasonProductChannelOnlineThirdPlatformMapper.delete(new QueryWrapper<SeasonProductChannelOnlineThirdPlatform>().lambda().eq(SeasonProductChannelOnlineThirdPlatform::getProductId, productId));
        //删除加幅日期
        List<Long> idList = seasonProductStrategyMapper.queryStrategyByProductId(productId);
        idList.forEach(id -> {
            seasonProductStrategyVaildDateMapper.deleteById(id);
        });
        //删除加幅
        seasonProductStrategyMapper.delete(new QueryWrapper<SeasonProductStrategy>().lambda().eq(SeasonProductStrategy::getSeasonProductId, productId));
    }


    /* @MethodName: 保存固定套票 加幅策略信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/15 18:57
     **/
    private boolean addSeasonProductStrategy(List<SeasonProductStrategyReq> reqList, Long userId, Long productId) {
        //是否上架 当所有加幅策略中 只有一个满足 就算上架
        List<Integer> list = new LinkedList<>();
        LocalDateTime now = LocalDateTime.now();
        int isDeleteCode = IsDeletedCode.NO.getCode();
        //多个加幅策略
        for (SeasonProductStrategyReq req : reqList) {
            //固定套票加幅表
            SeasonProductStrategy seasonProductStrategy = new SeasonProductStrategy();
            seasonProductStrategy.setCostName(req.getCostName());
            seasonProductStrategy.setSeasonProductId(productId);//产品id
            seasonProductStrategy.setCreateId(userId);
            seasonProductStrategy.setIsDeleted(isDeleteCode);
            Long seasonProductStrategyId = SnowflakeIdWorker.nextId();//雪花算法
            seasonProductStrategy.setId(seasonProductStrategyId);
            seasonProductStrategy.setGmtCreate(now);
            seasonProductStrategyMapper.insert(seasonProductStrategy);
            //加幅设置有效期
            List<SeasonProductStrategyVaildDateReq> dateList = req.getSeasonProductStrategyVaildDateList();
            List<SeasonProductStrategyVaildDate> batchList = new LinkedList<>();
            for (SeasonProductStrategyVaildDateReq dateReq : dateList) {
                SeasonProductStrategyVaildDate strategyVaildDate = new SeasonProductStrategyVaildDate();
                strategyVaildDate.setTimeBegin(dateReq.getTimeBegin());
                strategyVaildDate.setTimeEnd(dateReq.getTimeEnd());
                strategyVaildDate.setStrategyId(seasonProductStrategyId);
                strategyVaildDate.setCreateId(userId);
                strategyVaildDate.setIsDeleted(isDeleteCode);
                strategyVaildDate.setGmtCreate(now);
                strategyVaildDate.setId(SnowflakeIdWorker.nextId());
                batchList.add(strategyVaildDate);
            }
            seasonProductStrategyVaildDateMapper.insertBatchSomeColumn(batchList);
            boolean flag = addIncreaseStrategy(req, userId, productId, seasonProductStrategyId);
            if (flag) {
                list.add(1);
            }
        }
        return list.size() > 0 ? true : false;
    }

    /**
     * 保存 策略具体的 设置信息
     *
     * @param req
     * @param userId                  用户id
     * @param productId               固定产品id
     * @param seasonProductStrategyId 策率id
     * @return
     */
    private boolean addIncreaseStrategy(SeasonProductStrategyReq req, Long userId, Long productId, Long seasonProductStrategyId) {
        boolean onShelfStatus = false;
        LocalDateTime now = LocalDateTime.now();
        int isDeleteCode = IsDeletedCode.NO.getCode();
        //线下自营渠道 自定义用户部门集合
        List<SeasonProductChannelOfflineSelfCustomReq> selfCustomReqList = req.getSeasonProductChannelOfflineSelfCustomList();
        //线下渠道 代理商
        List<SeasonProductChannelOfflineAgentCustomReq> agentCustomReqList = req.getSeasonProductChannelOfflineAgentCustomList();
        //线上官方平台
        List<SeasonProductChannelOnlineSelfPlatformReq> selfPlatformReqList = req.getSeasonProductChannelOnlineSelfPlatformList();
        //线上第三方平台
        List<SeasonProductChannelOnlineThirdPlatformReq> thirdPlatformList = req.getSeasonProductChannelOnlineThirdPlatformList();
        LinkedList<Integer> isProhibitionList = new LinkedList<>();//是否是禁售卖
        //这个产品中心 线下 渠道 自营渠道
        if (null != selfCustomReqList && selfCustomReqList.size() > 0) {//当不为空
            for (SeasonProductChannelOfflineSelfCustomReq selfCustomReq : selfCustomReqList) {
                boolean isProhibition = selfCustomReq.getVisableType() != null && selfCustomReq.getVisableType() != 1;
                if (isProhibition) {//不是禁售
                    isProhibitionList.add(1);
                }
                long selfCustomId = SnowflakeIdWorker.nextId();
                SeasonProductChannelOffline channelOffline = EntityUtil.copy(selfCustomReq, SeasonProductChannelOffline.class);
                channelOffline.setCreateId(userId);
                channelOffline.setIsDeleted(isDeleteCode);
                channelOffline.setProductId(productId);
                channelOffline.setGmtCreate(now);
                channelOffline.setId(selfCustomId);
                channelOffline.setStrategyId(seasonProductStrategyId);
                seasonProductChannelOfflineMapper.insert(channelOffline);
                //自营下渠道下的 具体设置信息
                List<SeasonProductChannelOfflineSelfCustomArrayReq> selfCustomArrayReqs = selfCustomReq.getProductChannelOfflineSelfCustomArray();
                //当有元素的时候
                if (null != selfCustomArrayReqs && selfCustomArrayReqs.size() > 0) {
                    List<SeasonProductChannelOfflineSelfCustom> selfCustomList = selfCustomArrayReqs.stream().map(arrayReq -> {
                        SeasonProductChannelOfflineSelfCustom selfCustom = EntityUtil.copy(arrayReq, SeasonProductChannelOfflineSelfCustom.class);
                        selfCustom.setId(SnowflakeIdWorker.nextId());
                        selfCustom.setCreateId(userId);
                        selfCustom.setIsDeleted(isDeleteCode);
                        selfCustom.setGmtCreate(now);
                        selfCustom.setOfflineId(selfCustomId);
                        selfCustom.setProductId(productId);
                        return selfCustom;
                    }).collect(Collectors.toList());
                    seasonProductChannelOfflineSelfCustomMapper.insertBatchSomeColumn(selfCustomList);
                } else {
                    if (isProhibition) {//当不是 禁售 下面没有设置值 就要返回
                        new BusinessException(SystemError.SEASON_TICKET_20009);
                    }
                }

            }
        }
        //这个产品中心 线下 渠道 代理商
        if (null != agentCustomReqList && agentCustomReqList.size() > 0) {//当不为空
            for (SeasonProductChannelOfflineAgentCustomReq agenCustomReq : agentCustomReqList) {
                boolean isProhibition = agenCustomReq.getVisableType() != null && agenCustomReq.getVisableType() != 1;
                if (isProhibition) {//不是禁售
                    isProhibitionList.add(1);
                }
                long selfCustomId = SnowflakeIdWorker.nextId();
                SeasonProductChannelOffline channelOffline = EntityUtil.copy(agenCustomReq, SeasonProductChannelOffline.class);
                channelOffline.setCreateId(userId);
                channelOffline.setIsDeleted(isDeleteCode);
                channelOffline.setProductId(productId);
                channelOffline.setGmtCreate(now);
                channelOffline.setId(selfCustomId);
                channelOffline.setStrategyId(seasonProductStrategyId);
                seasonProductChannelOfflineMapper.insert(channelOffline);
                //代理渠道下的 具体设置信息
                List<SeasonProductChannelOfflineAgentCustomArrayReq> agentCustomArrayReqs = agenCustomReq.getProductChannelOfflineAgentCustomArray();
                //当有元素的时候
                if (null != agentCustomArrayReqs && agentCustomArrayReqs.size() > 0) {
                    List<SeasonProductChannelOfflineAgentCustom> agentCustomList = agentCustomArrayReqs.stream().map(arrayReq -> {
                        SeasonProductChannelOfflineAgentCustom agentCustom = EntityUtil.copy(arrayReq, SeasonProductChannelOfflineAgentCustom.class);
                        agentCustom.setId(SnowflakeIdWorker.nextId());
                        agentCustom.setCreateId(userId);
                        agentCustom.setIsDeleted(isDeleteCode);
                        agentCustom.setGmtCreate(now);
                        agentCustom.setOfflineId(selfCustomId);
                        agentCustom.setProductId(productId);
                        return agentCustom;
                    }).collect(Collectors.toList());
                    seasonProductChannelOfflineAgentCustomMapper.insertBatchSomeColumn(agentCustomList);
                } else {
                    if (isProhibition) {//当不是 禁售 下面没有设置值 就要返回
                        new BusinessException(SystemError.SEASON_TICKET_20010);
                    }
                }

            }
        }
        //这个产品中心 线上渠道 官方平台
        if (null != selfPlatformReqList && selfPlatformReqList.size() > 0) {
            isProhibitionList.add(1);
            List<SeasonProductChannelOnlineSelfPlatform> selfPlatformList = selfPlatformReqList.stream().map(arrayReq -> {
                SeasonProductChannelOnlineSelfPlatform onlineSelfPlat = EntityUtil.copy(arrayReq, SeasonProductChannelOnlineSelfPlatform.class);
                onlineSelfPlat.setId(SnowflakeIdWorker.nextId());
                onlineSelfPlat.setCreateId(userId);
                onlineSelfPlat.setIsDeleted(isDeleteCode);
                onlineSelfPlat.setGmtCreate(now);
                onlineSelfPlat.setProductId(productId);
                onlineSelfPlat.setStrategyId(seasonProductStrategyId);
                return onlineSelfPlat;
            }).collect(Collectors.toList());
            seasonProductChannelOnlineSelfPlatformMapper.insertBatchSomeColumn(selfPlatformList);
        }
        //这个产品中心 线上渠道 第三方平台
        if (null != thirdPlatformList && thirdPlatformList.size() > 0) {
            isProhibitionList.add(1);
            List<SeasonProductChannelOnlineThirdPlatform> onlineThirdPlatformList = thirdPlatformList.stream().map(arrayReq -> {
                SeasonProductChannelOnlineThirdPlatform onlineThirdPlat = EntityUtil.copy(arrayReq, SeasonProductChannelOnlineThirdPlatform.class);
                onlineThirdPlat.setId(SnowflakeIdWorker.nextId());
                onlineThirdPlat.setCreateId(userId);
                onlineThirdPlat.setIsDeleted(isDeleteCode);
                onlineThirdPlat.setGmtCreate(now);
                onlineThirdPlat.setProductId(productId);
                onlineThirdPlat.setStrategyId(seasonProductStrategyId);
                return onlineThirdPlat;
            }).collect(Collectors.toList());
            seasonProductChannelOnlineThirdPlatformMapper.insertBatchSomeColumn(onlineThirdPlatformList);
        }
        return isProhibitionList.size() > 0 ? true : false;
    }


    /* @MethodName: 根据固定套票产品id  获取该产品下的 加幅策略
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/15 18:04
     **/
    public List<SeasonProductStrategy> getSeasonProductStrategyList(Long seasonProductId) {
        return seasonProductStrategyMapper.selectList(
                new QueryWrapper<SeasonProductStrategy>().lambda().eq(SeasonProductStrategy::getSeasonProductId, seasonProductId)
                        .eq(SeasonProductStrategy::getIsDeleted, IsDeletedCode.NO.getCode())
        );

    }

}
